package com.jswdwsx.esign.cloud

import com.fasterxml.jackson.databind.ObjectMapper
import com.jswdwsx.esign.cloud.exception.EsignException
import feign.Response
import feign.Util
import feign.codec.ErrorDecoder
import org.slf4j.LoggerFactory
import java.io.IOException

open class ExceptionErrorDecoder(private var objectMapper: ObjectMapper = ObjectMapper()) : ErrorDecoder {
    private val logger = LoggerFactory.getLogger(ExceptionErrorDecoder::class.java)

    override fun decode(s: String, response: Response): Exception {
        val reader = response.body().asReader()
        val body = Util.toString(reader)
        logger.info("feign接口url:${response.request().url()},body:$body")
        val javaType =
            objectMapper.typeFactory.constructParametricType(Map::class.java, String::class.java, String::class.java)
        try {
            val map: Map<String, String> = objectMapper.readValue(body, javaType)
            return EsignException(
                map.getValue("code"),
                map.getValue("message")
            )
        } catch (e: IOException) {
            logger.warn("字符串转List失败，{}", e.message)
        }
        return EsignException("500", "未知异常")
    }
}